/*
 * AdminPurchaseInfo.java
 *
 * Created on Jan 14, 2011, 4:07:30 PM
 */
package edu.rit.varapp.graphical;

import edu.rit.varapp.datalayer.Customer;
import edu.rit.varapp.datalayer.CustomerOps;
import edu.rit.varapp.datalayer.Module;
import edu.rit.varapp.datalayer.ModuleOps;
import edu.rit.varapp.utilities.ExceptionUtils;
import edu.rit.varapp.utilities.JTableUtils;
import java.awt.Dimension;
import java.awt.event.KeyEvent;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

/**
 *
 * @author Eric Kisner
 */
public class AdminPurchaseInfo extends AbstractView {

    private static final int VIEW_WIDTH = 836;
    private static final int VIEW_HEIGHT = 514;
    private final CustomerOps cOps = new CustomerOps();
    private final ModuleOps mOps = new ModuleOps();
    private JTable customerTable = null;
    private JTable modulesTable = null;
    private Customer customer;
    private int serialNumber = -1;

    /** Creates new form AdminPurchaseInfo */
    public AdminPurchaseInfo() {
        super( new Dimension( VIEW_WIDTH, VIEW_HEIGHT ) );
        initComponents();
    }

    private void setCustomerTable( JTable customerTable ) {
        this.customerTable = customerTable;
    }

    private void setCustomer( Customer customer ) {
        this.customer = customer;
    }

    private void setModulesTable( JTable modulesTable ) {
        this.modulesTable = modulesTable;
    }

    private void setSerialNumber( int serialNumber ) {
        this.serialNumber = serialNumber;
    }

    public void refreshGUI() {
        if( customerTable != null ) {
            customerTableHolder.removeAll();
            if( modulesTable != null ) {
                moduleTableHolder.removeAll();
            }
            this.repaint();
            this.validate();
        }
        showCustomers( customernameField.getText() );
        this.repaint();
        this.validate();
    }

    /**
     * Get any Customer information associated with the specified customer name and display all information in
     * a JTable.
     * @param customerName The customer's name whose information we're looking for. There could be multiple people
     *                     with the same name.
     */
    private void showCustomers( String customerName ) {
        ArrayList<Customer> customers = null;
        try {
            customers = cOps.retrieveCustomers( customerName );
        } catch( SQLException sqle ) {
            ExceptionUtils.handleException( this, sqle,
                                            "There was an error retrieving information for customer "
                                            + customerName + ".\nPlease check the log files for more details.",
                                            this.getClass() );
            return;
        }
        if( customers.isEmpty() ) {
            JOptionPane.showMessageDialog( this, "The customer name " + customerName + " did not return any results." );
            return;
        }
        String[] header = { "Title", "Contact Name", "Company Name", "Email" };
        JTable table = JTableUtils.getCustomerTable( header, customers, false );
        table = applyOptions( table, true );
        setCustomerTable( table );
        JScrollPane holder = new JScrollPane( table );
        customerTableHolder.add( holder );
        holder.setBounds( 0, 0, 780, 180 );
    }

    /**
     * Get all Module information associated with the selected customer and show it in a JTable.
     */
    private void showModules() {
        moduleTableHolder.removeAll();
        this.repaint();
        this.validate();
        ArrayList<Module> modules = null;
        try {
            modules = mOps.retrieveModules( customer.getEntityId() );
        } catch( SQLException sqle ) {
            ExceptionUtils.handleException( this, sqle,
                                            "There was an error retrieving module information for the selected"
                                            + " customer.\nPlease check the log file for more details.",
                                            AdminPurchaseInfo.class );
            return;
        }

        if( modules.isEmpty() ) {
            JOptionPane.showMessageDialog( this, "The selected customer does not have any module information." );
            return;
        }
        String[] header = { "Serial Number", "License Code", "Location" };
        JTable table = JTableUtils.getModuleTable( header, modules, false );
        table = applyOptions( table, false );
        setModulesTable( table );
        JScrollPane holder = new JScrollPane( table );
        moduleTableHolder.add( holder );
        holder.setBounds( 0, 0, 780, 180 );
    }

    /**
     * Add options to the JTable before displaying it.
     * @param isCustomerTable Flag to say if this is a Customer JTable or Modules JTable.
     */
    private JTable applyOptions( final JTable table, boolean isCustomerTable ) {
        //Get any data of this JTable as a collectiong of rows
        final ArrayList<ArrayList<String>> data = JTableUtils.dataFromTable( table );
        table.setRowHeight( 30 );
        table.setRowMargin( 10 );
        table.setSelectionMode( javax.swing.ListSelectionModel.SINGLE_SELECTION );
        table.setShowHorizontalLines( false );
        table.setShowVerticalLines( false );

        //Add a selection listener to the table to listen to user selection.
        if( isCustomerTable ) { //Customer table
            table.getSelectionModel().addListSelectionListener( new ListSelectionListener() {

                public void valueChanged( ListSelectionEvent e ) {
                    if( e.getValueIsAdjusting() ) {
                        return;
                    }
                    //Since the table uses single_selection, there can only be one row selected at a time
                    final int curRow = table.getSelectionModel().getLeadSelectionIndex();
                    //Get the customer information of the current selected row
                    ArrayList<String> customerData = data.get( curRow );
                    //Get the EntityId of the selected customer by using their company name and contact name
                    try {
                        Customer customer = cOps.retrieveCustomer( customerData.get( 1 ), customerData.get( 2 ) );
                        setCustomer( customer );
                        showModules();
                    } catch( SQLException sqle ) {
                        ExceptionUtils.handleException( AdminPurchaseInfo.this, sqle,
                                                        "There was an error retrieving information for customer "
                                                        + customerData.get( 1 )
                                                        + ".\nPlease check the log files for more information.",
                                                        AdminPurchaseInfo.class );
                        return;
                    }
                }
            } );
        } else {    //Module table
            table.getSelectionModel().addListSelectionListener( new ListSelectionListener() {

                public void valueChanged( ListSelectionEvent e ) {
                    if( !e.getValueIsAdjusting() ) {
                        //Since the table uses single_selection, there can only be one row selected at a time
                        final int curRow = table.getSelectionModel().getLeadSelectionIndex();
                        //Get the module information of the current selected row
                        ArrayList<String> moduleData = data.get( curRow );
                        //Get the SerialNumber of the selected module
                        int serialNumber = Integer.valueOf( moduleData.get( 0 ) );
                        setSerialNumber( serialNumber );
                    }
                }
            } );
        }
        return table;
    }

    /**
     * Display the selected module information in another view.
     */
    private void displayModuleInfo( int serialNumber ) {
        try {
            Module module = mOps.retrieveModule( serialNumber );
            new DisplayPurchase( this, module, customer ).setVisible( true );
            this.setVisible( false );
        } catch( SQLException sqle ) {
            ExceptionUtils.handleException( this, sqle, "There was an error retrieving module "
                                                        + "information for serial number " + serialNumber
                                                        + ".\nPlease check the log file for more details.",
                                            this.getClass() );
            return;
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings( "unchecked" )
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        viewInfoButton = new javax.swing.JButton();
        customerTableHolder = new javax.swing.JPanel();
        moduleTableHolder = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        customernameField = new javax.swing.JTextField();
        getCustomerButton = new javax.swing.JButton();
        backButton = new javax.swing.JButton();
        deletePurchaseButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Purchase Information");
        setMinimumSize(new java.awt.Dimension(836, 514));
        setResizable(false);
        getContentPane().setLayout(null);

        viewInfoButton.setText("View Info");
        viewInfoButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                viewInfoButtonActionPerformed(evt);
            }
        });
        getContentPane().add(viewInfoButton);
        viewInfoButton.setBounds(180, 450, 140, 23);

        customerTableHolder.setBorder(javax.swing.BorderFactory.createTitledBorder("Customer Information"));
        customerTableHolder.setLayout(null);
        getContentPane().add(customerTableHolder);
        customerTableHolder.setBounds(20, 50, 780, 180);

        moduleTableHolder.setBorder(javax.swing.BorderFactory.createTitledBorder("Purchase Info"));
        moduleTableHolder.setLayout(null);
        getContentPane().add(moduleTableHolder);
        moduleTableHolder.setBounds(20, 250, 780, 180);

        jPanel2.setLayout(new java.awt.GridLayout(1, 3, 2, 0));

        jLabel1.setText("Enter Customer Name:");
        jPanel2.add(jLabel1);

        customernameField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                customernameFieldKeyPressed(evt);
            }
        });
        jPanel2.add(customernameField);

        getCustomerButton.setText("Get Customer Information");
        getCustomerButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                getCustomerButtonActionPerformed(evt);
            }
        });
        jPanel2.add(getCustomerButton);

        getContentPane().add(jPanel2);
        jPanel2.setBounds(10, 10, 590, 30);

        backButton.setText("Back");
        backButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                backButtonActionPerformed(evt);
            }
        });
        getContentPane().add(backButton);
        backButton.setBounds(500, 450, 140, 23);

        deletePurchaseButton.setText("Delete Purchase");
        deletePurchaseButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deletePurchaseButtonActionPerformed(evt);
            }
        });
        getContentPane().add(deletePurchaseButton);
        deletePurchaseButton.setBounds(340, 450, 140, 23);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void getCustomerButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_getCustomerButtonActionPerformed
        refreshGUI();
    }//GEN-LAST:event_getCustomerButtonActionPerformed

    private void backButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_backButtonActionPerformed
    {//GEN-HEADEREND:event_backButtonActionPerformed
        new AdminOperations().setVisible( true );
        close( false );
    }//GEN-LAST:event_backButtonActionPerformed

    private void customernameFieldKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_customernameFieldKeyPressed
        if( evt.getKeyCode() == KeyEvent.VK_ENTER ) {
            refreshGUI();
        }
    }//GEN-LAST:event_customernameFieldKeyPressed

    private void viewInfoButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_viewInfoButtonActionPerformed
        if( serialNumber > -1 ) {
            displayModuleInfo( serialNumber );
        }
    }//GEN-LAST:event_viewInfoButtonActionPerformed

    private void deletePurchaseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deletePurchaseButtonActionPerformed
        try {
            boolean success = mOps.deleteModule( mOps.retrieveModule( serialNumber ) );
            if( success ) {
                JOptionPane.showMessageDialog( rootPane, "Successfully deleted this module." );
                refreshGUI();
            } else {
                refreshGUI();
            }
        } catch( SQLException sqle ) {
            ExceptionUtils.handleException( this, sqle, "There was a problem deleting this module. "
                                                        + "Please check the log file for more information.",
                                            this.getClass() );
            return;
        }
    }//GEN-LAST:event_deletePurchaseButtonActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton backButton;
    private javax.swing.JPanel customerTableHolder;
    private javax.swing.JTextField customernameField;
    private javax.swing.JButton deletePurchaseButton;
    private javax.swing.JButton getCustomerButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel moduleTableHolder;
    private javax.swing.JButton viewInfoButton;
    // End of variables declaration//GEN-END:variables
}
